import unittest
import requests
import time


class TestAPI(unittest.TestCase):
    base_url = "http://182.151.48.185:8098/api/private/v1/"

    @classmethod
    def setUpClass(cls):
        cls.header = {
            "Authorization": cls.test_login(cls)
        }

    def test_login(self):
        url = self.base_url + "login"
        admin_info = {
            "username": "admin",
            "password": "123456"
        }
        req = requests.post(url, json=admin_info)
        token = req.json()["data"]["token"]
        return token

    def test_addUser(self):
        url = self.base_url + "users"
        current_time = time.strftime("%Y%m%d%H%M%S", time.localtime())
        username = "XX"
        user_info = {
            "username": username + current_time,
            "password": "02212456",
            "email": "14QW9F8QWF49@qq.com",
        }
        req = requests.post(url, json=user_info, headers=self.header)

        self.assertEqual(200, req.status_code)
        self.assertIn("创建成功", req.text)
        self.assertEqual(user_info["username"], req.json()['data']['username'])

    def test_GetuserId(self,):
        url = self.base_url + "users/{0}".format(1643)
        req = requests.get(url, headers=self.header)
        print(req.json())
        self.assertEqual(200, req.status_code)
        self.assertIn("获取成功", req.text)
        self.assertIn("XX", req.json()['data']['username'])

    def test_UserByPage(self):
        url = self.base_url + "users"
        p = {
            "pagenum": "1",
            "pagesize": "10"
        }
        req = requests.get(url, params=p, headers=self.header)
        self.assertEqual(200, req.status_code)
        self.assertIn("获取管理员列表成功", req.text)
        self.assertEqual(p['pagesize'], str(len(req.json()['data']['users'])))


if __name__ == "__main__":
    unittest.main()